"use strict";
define(["jquery","template","echarts"], function ($,template,echarts) {
(function ($) {
    var PieChars = function () {
        function PieChars(el, options) {
            this.id = 'pieChars' + Math.round(Math.random() * 1000000000); //实例唯一ID名
            this.defalut = {
                type: "", //布局方式 |vertical
                name: "",
                subName: "",
                data: [] //数据
            };
            this._set = $.extend(this._defaluts, options);
            this.settings = $.extend(true, this.defalut, options, {
                id: this.id
            } || []);
            this.el = el;
            this.init();
        };
        PieChars.prototype = {
            init: function init() {
                var option = this.settings;
                this.initHtml();
                this.initAttributes();
                this.initChars();
                this.initEvens();
            },
            initHtml: function initHtml() {
                var html = "<div class=\"pieChars-wrap\">\n                <div class=\"chars\"></div>\n                <div class=\"chars-btn-wrap\">\n                    <div class=\"chars-btn prev disabled\"></div>\n                    <div class=\"chars-btn middle\"></div>\n                    <div class=\"chars-btn next\"></div>\n                </div>\n                <div class=\"box\"></div>\n                <div class=\"circle-bg\"><span class=\"point\"></span></div>\n                </div>";
                var tplHtml = template.compile(html);
                $(this.el).html(tplHtml());
                $(this.el).addClass("pieChars");
                if (this.settings.type === "vertical") {
                    $(this.el).attr("vertical", "");
                }
            },
            initChars: function initChars() {
                this.myChart = echarts.init(document.getElementById(this.settings.id));
                this.myChart.setOption(this.initOption("#" + this.settings.id, this.settings, this.el));
            },
            setWH: function setWH(width, height, type, data) {
                var pieDia, piefontSize, padding, sliceLen, lastWidth, valueWidth, paddingTop;
                var hasSum = true;
                switch (type) {
                    case "vertical":
                        //上下布局
                        if (height >= 296) {
                            pieDia = 100;
                            piefontSize = 24;
                            padding = 24;
                            paddingTop = 16;
                        } else if (height < 296 && height >= 256) {
                            pieDia = 80;
                            piefontSize = 18;
                            padding = 24;
                            paddingTop = 16;
                        } else if (height < 256 && height >= 188) {
                            pieDia = 60;
                            piefontSize = 18;
                            padding = 12;
                            paddingTop = 0;
                        } else {
                            pieDia = 60;
                            piefontSize = 18;
                            padding = 12;
                            paddingTop = 0;
                        }
                        if (width < 368 && width >= 348) {
                            hasSum = false;
                        } else if (width < 348 && width >= 328) {
                            hasSum = false;
                        } else if (width < 328 && width >= 228) {
                            hasSum = false;
                        }

                        var lastWidth = (width - padding * 2) / 2;
                        var valueWidth = lastWidth - 50 - 30 - 8;
                        sliceLen = Math.round(valueWidth / 12);

                        if (!hasSum) {
                            valueWidth = (width - padding * 2) / 2 - 24;
                            sliceLen = Math.round(valueWidth / 12);
                        }
                        break;
                    default:
                        //左右布局
                        //高最大为180
                        if (height >= 180) {
                            pieDia = 90;
                            piefontSize = 24;
                            padding = 24;
                        } else if (height < 180 && height >= 160) {
                            pieDia = height / 2;
                            piefontSize = 18;
                            padding = 24;
                        } else if (height < 160 && height >= 120) {
                            pieDia = height / 2;
                            piefontSize = 18;
                            padding = 12;
                        } else {
                            pieDia = 60;
                            piefontSize = 18;
                            padding = 12;
                        }

                        if (width >= 368) {} else if (width < 368 && width >= 348) {
                            hasSum = false;
                        } else if (width < 348 && width >= 328) {
                            hasSum = false;
                            padding = 12;
                        } else if (width < 328 && width >= 228) {
                            pieDia = 60;
                            hasSum = false;
                            piefontSize = 18;
                            padding = 12;
                        }

                        var lastWidth = width - pieDia * 2 - 30;
                        var valueWidth = lastWidth - 50 - padding * 2;
                        sliceLen = Math.round(valueWidth / 12);

                        if (!hasSum) {
                            valueWidth = width - pieDia * 2 - padding * 2 - 24;
                            sliceLen = Math.round(valueWidth / 12);
                        }

                        break;
                };
                return {
                    width: width,
                    height: height,
                    pieDia: pieDia,
                    sliceLen: sliceLen,
                    piefontSize: piefontSize,
                    hasSum: hasSum,
                    padding: padding,
                    lastWidth: lastWidth,
                    valueWidth: valueWidth,
                    paddingTop: paddingTop,
                    type: type,
                    data: data
                };
            },
            initOption: function initOption(el, newData) {
                var that = this;
                var width = $(el).width();
                var height = $(el).height();
                var optionData = this.setWH(width, height, newData.type, newData.data);
                console.log(optionData);
                var sum = 0;
                newData.data.forEach(function (item) {
                    sum += item.value;
                });

                var pieDia = optionData.pieDia;
                var piefontSize = optionData.piefontSize;
                var sliceLen = optionData.sliceLen;
                var padding = optionData.padding;
                var paddingTop = optionData.paddingTop;
                var hasSum = optionData.hasSum;
                var valueWidth = optionData.valueWidth;
                var option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    series: [{
                        name: '耗能总量',
                        type: 'pie',
                        radius: [pieDia * .7, pieDia * .9],
                        center: [pieDia + padding, "50%"],
                        color: ["#0167D2", "#0199D2", "#00F6FF", "#5DE17F", "#DCE160", "#EB965D", "#DF5D60", "#9535DB", "#3453DB"],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            normal: {
                                borderColor: "#030F1C",
                                borderWidth: 2
                            }
                        },
                        hoverOffset: 8,
                        label: {
                            position: 'center',
                            formatter: function formatter(data) {
                                if (data.seriesIndex == "0") {
                                    return "{a|" + addChineseUnit(sum, 2) + "}\n{b|" + newData.subName + "}";
                                } else {
                                    return "";
                                }
                            },
                            rich: {
                                a: {
                                    color: '#fff',
                                    fontSize: piefontSize,
                                    fontWeight: "bold",
                                    borderRadius: 6,
                                    align: "center",
                                    backgroundColor: "rgba(3, 15, 28, 0.1)",
                                    padding: 4
                                },
                                b: {
                                    padding: 8,
                                    color: "#fff",
                                    fontSize: piefontSize - 10 > 12 ? piefontSize - 10 : 12,
                                    align: "center",
                                    fontWeight: "normal"
                                }
                            }
                        },
                        emphasis: {},
                        labelLine: {
                            show: false
                        },
                        data: newData.data
                    }]

                };

                $("#" + newData.id).parent().find('.circle-bg').height(pieDia * 2);
                $("#" + newData.id).parent().find('.circle-bg').width(pieDia * 2);
                $(el).parent().find('.circle-bg').css("left", padding);

                //上下布局
                if (newData.type === "vertical") {
                    $(el).parent().find('.circle-bg').css("left", "50%");
                    that.currentIndex = 1;
                    that.total = Math.ceil(newData.data.length / 2) - 1;
                    $(el).parent().find('.middle').html(that.currentIndex + "/" + that.total);
                    if (newData.data.length <= 4) {
                        $("#" + newData.id).parent().find('.box').hide();
                        $("#" + newData.id).parent().find('.chars-btn-wrap').hide();
                    }

                    $("#" + newData.id).parent().find('.box').css({
                        "top": pieDia * 2 + paddingTop - 1,
                        "left": padding,
                        "width": "calc(100% - " + padding * 2 + "px)"
                    });
                    var data1 = [];
                    var data2 = [];
                    newData.data.forEach(function (item, index) {
                        if (index % 2 == 1) {
                            data2.push(item);
                        } else {
                            data1.push(item);
                        }
                    });
                    $("#" + newData.id).parent().find('.chars-btn-wrap').css("top", pieDia * 2 + 48 + paddingTop);
                    option.series[0].center = ["50%", pieDia];
                    var legend = {
                        id: newData.id + 111,
                        top: pieDia * 2 + paddingTop,
                        height: 56,
                        data: data1,
                        type: "scroll",
                        orient: "vertical",
                        pageIconColor: "#00F6FF",
                        pageIconInactiveColor: "#8BADD2",
                        pageButtonGap: 8,
                        pageIconSize: 0,
                        pageFormatter: "",
                        pageTextStyle: {
                            color: "#CDCFD2"
                        },
                        icon: "circle",
                        width: width - 32,
                        itemHeight: 8,
                        itemWidth: 8,
                        formatter: function formatter(name) {
                            var value = arraytomap(newData.data)[name].value;
                            if (hasSum) {
                                return "{a|" + (name.length >= sliceLen ? name.slice(0, sliceLen - 1) + '...' : name) + "} {b|" + addChineseUnit(value, 2) + "}";
                            } else {
                                return "{c|" + (name.length >= sliceLen ? name.slice(0, sliceLen - 1) + '...' : name) + "}";
                            }
                        },
                        textStyle: {
                            color: "#8CBDD2",
                            rich: {
                                a: {
                                    width: valueWidth,
                                    lineHeight: 16
                                },
                                b: {
                                    color: '#fff',
                                    width: 50,
                                    align: "right"
                                },
                                c: {
                                    width: valueWidth
                                }
                            }
                        }
                    };
                    var len1 = $.extend({}, legend);
                    var len2 = $.extend({}, legend);
                    len1.left = padding + 8;
                    len2.id = newData.id + 222;
                    len2.data = data2;
                    len2.right = padding + 8;
                    option.legend = [len1, len2];
                }
                //左右布局
                else {
                        $("#" + newData.id).parent().find('.chars-btn-wrap').hide();
                        $("#" + newData.id).parent().find('.box').hide();
                        option.legend = {
                            data: newData.data,
                            textStyle: {
                                color: "#8CBDD2",
                                rich: {
                                    a: {
                                        width: valueWidth
                                    },
                                    b: {
                                        color: '#fff',
                                        width: 50,
                                        align: "right"
                                    },
                                    c: {
                                        width: valueWidth
                                    }
                                }
                            },
                            formatter: function formatter(name) {
                                var value = arraytomap(newData.data)[name].value;
                                if (hasSum) {
                                    return "{a|" + (name.length >= sliceLen ? name.slice(0, sliceLen - 1) + '...' : name) + "} {b|" + addChineseUnit(value, 2) + "}";
                                } else {
                                    return "{c|" + (name.length >= sliceLen ? name.slice(0, sliceLen - 1) + '...' : name) + "}";
                                }
                            },
                            orient: "vertical",
                            type: "scroll",
                            top: "center",
                            height: 124,
                            left: pieDia * 2 + padding * 1.8,
                            pageIconColor: "#00F6FF",
                            pageIconInactiveColor: "#8BADD2",
                            pageButtonGap: 8,
                            pageIconSize: 12,
                            pageTextStyle: {
                                color: "#CDCFD2"
                            },
                            icon: "circle",
                            itemHeight: 8,
                            itemWidth: 8
                        };
                        if (height < 160 && height >= 120) {
                            option.legend.height = 80;
                        }
                    }
                console.log(option);

                return option;
            },
            initAttributes: function initAttributes() {
                $(this.el).find('.chars').attr("id", this.settings.id);
            },
            moveLegend: function moveLegend(index, total) {
                var el = this.el;
                var option = this.settings;
                this.myChart.dispatchAction({
                    type: 'legendScroll',
                    scrollDataIndex: index - 1,
                    legendId: option.id + 111
                });
                this.myChart.dispatchAction({
                    type: 'legendScroll',
                    scrollDataIndex: index - 1,
                    legendId: option.id + 222
                });
                $(el).find('.disabled').removeClass('disabled');
                if (index <= 1) {
                    this.currentIndex = 1;
                    $(el).find('.prev').addClass('disabled');
                } else if (index >= total) {
                    this.currentIndex = total;
                    $(el).find('.next').addClass('disabled');
                }
                $(el).find('.middle').html(index + "/" + total);
            },
            //注册组件事件
            initEvens: function initEvens() {
                var el = this.el; //组件实例容器
                var that = this;
                var option = this.settings;
                $(el).on('click', '.prev', function () {
                    that.currentIndex--;
                    that.moveLegend(that.currentIndex, that.total);
                });
                $(el).on('click', '.next', function () {
                    that.currentIndex++;
                    that.moveLegend(that.currentIndex, that.total);
                });
                $(window).on("resize", function () {
                    that.myChart.setOption(that.initOption("#" + that.settings.id, that.settings, that.el));
                    that.myChart.resize();
                });
            }
        };
        return PieChars;
    }();
    $.fn.pieChars = function (options) {
        var ags = arguments;
        return this.each(function (index, item) {
            var el = $(item);
            var instance = el.data("pieChars");
            //判断实例是否存在
            if (!instance) {
                instance = new PieChars(el, options);
                //存放实例
                el.data("pieChars", instance);
            }
            //外部可以通过$(select).MultipleRowFilter("init")
            if ($.type(options) === "string") {
                return instance[options](ags);
            }
        });
    };
    //插件内部初始化，在目标元素上添加data-multipleRowFilter
    $(function () {
        $('[data-pieChars]').pieChars();
    });

    //数组转map
    function arraytomap(data) {
        var map = {};
        data.forEach(function (item) {
            map[item.name] = item;
        });
        return map;
    }

    function addWan(integer, number, mutiple, decimalDigit) {
        var digit = getDigit(integer);
        if (digit > 3) {
            var remainder = digit % 8;
            if (remainder >= 5) {
                // ‘十万’、‘百万’、‘千万’显示为‘万’ 
                remainder = 4;
            }
            return Math.round(number / Math.pow(10, remainder + mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + '万';
        } else {
            return Math.round(number / Math.pow(10, mutiple - decimalDigit)) / Math.pow(10, decimalDigit);
        }
    }

    function getDigit(integer) {
        var digit = -1;
        while (integer >= 1) {
            digit++;
            integer = integer / 10;
        }
        return digit;
    }

    function addChineseUnit(number, decimalDigit) {
        decimalDigit = decimalDigit == null ? 2 : decimalDigit;
        var integer = Math.floor(number);
        var digit = getDigit(integer);
        // ['个', '十', '百', '千', '万', '十万', '百万', '千万']; 
        var unit = [];
        if (digit > 3) {
            var multiple = Math.floor(digit / 8);
            if (multiple >= 1) {
                var tmp = Math.round(integer / Math.pow(10, 8 * multiple));
                unit.push(addWan(tmp, number, 8 * multiple, decimalDigit));
                for (var i = 0; i < multiple; i++) {
                    unit.push('亿');
                }
                return unit.join('');
            } else {
                return addWan(integer, number, 0, decimalDigit);
            }
        } else {
            return number;
        }
    }
})(jQuery);
})